import * as mars3d from "mars3d";

const configUrl = "config/newMap.json";

export let map: mars3d.Map // mars3d.Map三维地图对象
export let graphicLayer: mars3d.layer.GraphicLayer; // 矢量图层对象

export const eventTarget = new mars3d.BaseClass()
export const Cesium =  mars3d.Cesium;

let keyDownCode // 一直按着的键对应的code
let isEntityGraphic = true
let query // 高德 路径规划

// 初始化地图
export async function onMounted(id:string) { 
  let mapOptions = await mars3d.Util.fetchJson({ url: configUrl });
  

  map = new mars3d.Map(id, mapOptions);
  



  query = new mars3d.query.QueryRoute({
    service: mars3d.QueryServiceType.GAODE
  })

  // // 加载石化工厂模型
  // const tiles3dLayer = new mars3d.layer.TilesetLayer({
  //   name: "石化工厂",
  //   url: "http://data.mars3d.cn/3dtiles/max-shihua/tileset.json",
  //   position: { lng: 117.077158, lat: 31.659116, alt: -2.0 },
  //   maximumScreenSpaceError: 1,
  //   popup: "all"
  // })
  // map.addLayer(tiles3dLayer)



  const defaultContextmenuItems = map.getDefaultContextMenu() // 内置的默认右键菜单获取方法
  map.bindContextMenu(defaultContextmenuItems) // 可以删减defaultContextmenuItems数组内值

  PCBroswer()

  // 开场动画
  startAnimation()




  // 添加矢量图层
  graphicLayer = new mars3d.layer.GraphicLayer({
    isAutoEditing: true // 是否自动激活编辑
  })
  map.addLayer(graphicLayer)



    // 按键按下
    map.on(mars3d.EventType.keydown, function (e) {
      keyDownCode = e.keyCode // 一直按着的键对应的code
    })
  
    // 按键按下后释放
    map.on(mars3d.EventType.keyup, function (e) {
      keyDownCode = undefined
    })
  
  
  
    graphicLayer.on(mars3d.EventType.editStart, function (e) {
      console.log("开始编辑", e)
    })
    graphicLayer.on(mars3d.EventType.editMovePoint, function (e) {
      console.log("编辑修改了点", e)
    })
    graphicLayer.on(mars3d.EventType.editAddPoint, function (e) {
      console.log("编辑新增了点", e)
    })
    graphicLayer.on(mars3d.EventType.editRemovePoint, function (e) {
      console.log("编辑删除了点", e)
    })
    graphicLayer.on(mars3d.EventType.editStop, function (e) {
      console.log("停止编辑", e)
    })
    graphicLayer.on(mars3d.EventType.removeGraphic, function (e) {
      console.log("删除了对象", e)
    })
  
  
  
    bindLayerContextMenu()
  

    // 弹框
    addDemoGraphic()



  // 原点带波纹
  // addAnimatedIconPoint()
  addGroundRippleAtModel()
  addtopBGraphic()  //  自带的方法跳动
  // addBouncingBillboardAtModel() //  自己写的方法跳动



  // loadOldData()


}
    

export function PCBroswer() {
      // 针对不同终端的优化配置
  if (mars3d.Util.isPCBroswer()) {
    map.zoomFactor = 2.0; // 鼠标滚轮放大的步长参数

    // IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
      map.viewer.targetFrameRate = 20; // 限制帧率
      map.scene.requestRenderMode = false; // 取消实时渲染
    }
  } else {
    map.zoomFactor = 5.0; // 鼠标滚轮放大的步长参数

    // 移动设备上禁掉以下几个选项，可以相对更加流畅
    map.scene.requestRenderMode = false; // 取消实时渲染
    map.scene.fog.enabled = false;
    map.scene.skyAtmosphere.show = false;
    map.scene.globe.showGroundAtmosphere = false;
  }

  // 二三维切换不用动画
  if (map.viewer.sceneModePicker) {
    map.viewer.sceneModePicker.viewModel.duration = 0.0;
  }
}
  


export function startAnimation() {
  map.flyHome({ duration: 0 })

  // 开场动画
  map.openFlyAnimation({
    // duration1:4,
    // easingFunction1: Cesium.EasingFunction.QUINTIC_IN_OUT,
  }).then(() => {
    // 动画播放完成后回调
  })
}

export function stopAnimation() {
  map.camera.cancelFlight()
}

// 组件卸载之前销毁mars3d实例
export function destroy() {
  if (map) {
    map.destroy();
    map = null;
  }
  console.log("map销毁完成");
}

export  const iconText = ref('') 
 


// 加载数据
function loadOldData() {
  // if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
  //   // 本地不显示历史数据
  //   return
  // }

  mars3d.Util.fetchJson({ url: "https://data.mars3d.cn/file/geojson/mars3d-draw.json" }).then((json) => {
    console.log(json)
    const graphics = graphicLayer.loadGeoJSON(json, {  })
    console.log("加载演示数据", graphics)
  })
}


export async function drawPoint() {
  const graphic = await graphicLayer.startDraw({
    type:  "point" ,
    style: {
      pixelSize: 12,
      clampToGround: false, // 不贴地
      height: 35, // 离地5米
      color: "#3388ff",
      label: {
        // 不需要文字时，去掉label配置即可
        text: "可以同时支持文字",
        font_size: 20,
        color: "#ffffff",
        outline: true,
        outlineColor: "#000000",
        pixelOffsetY: -20
      }
    }
  })

  console.log("标绘完成", graphic.toJSON())
}


export async function drawLabel() {
  const graphic = await graphicLayer.startDraw({
    // type: isEntityGraphic ? "label" : "labelP",
    type:  "label" ,
    style: {
      text: "火星科技三维地球",
      color: "#0081c2",
      font_size: 20,
      outline: true,
      outlineColor: "#ffffff",
      outlineWidth: 2
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawMarker() {
  const graphic = await graphicLayer.startDraw({
    type:  "billboard" ,
    style: {
      image: "https://data.mars3d.cn/img/marker/mark-red.png",
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      label: {
        // 不需要文字时，去掉label配置即可
        text: "可以同时支持文字",
        font_size: 16,
        color: "#ffffff",
        background: true,
        backgroundColor	:"rgba(27, 21, 21, 0.8)",
        outline: true,
        outlineColor: "#000000",
        pixelOffsetY: -60
      }
    }
  })

  console.log("标绘完成", graphicLayer.toGeoJSON({ 
    propsFilter: ["color", "materialType"] // 保留特殊材质参数
  }))
}


export async function startDrawModel() {
  const graphic = await graphicLayer.startDraw({
    type: "model" ,
    style: {
      scale: 10,
      url: "https://data.mars3d.cn/gltf/mars/firedrill/xiaofangche.gltf"
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawPolyline(clampToGround: boolean) {
  // map.highlightEnabled = false
  // map.popup.enabled = false

  const graphic = await graphicLayer.startDraw({
    type:  "polyline" ,
    style: {
      color: clampToGround ? "#ffff00" : "#3388ff",
      width: 3,
      clampToGround
    },
    // 绘制时，外部自定义更新坐标,可以自定义处理特殊业务返回修改后的新坐标。
    updateDrawPosition: function (position, graphic) {
      if (keyDownCode === 67) {
        // 按下C键 ,限定在纬度线上
        position = updateDrawPosition(position, graphic.lastDrawPoint, 1)
      } else if (keyDownCode === 86) {
        // 按下V键 ,限定在经度线上
        position = updateDrawPosition(position, graphic.lastDrawPoint, 2)
      }
      return position
    }
    // 外部自定义校验坐标，return false 时坐标无效，不参与绘制
    // validDrawPosition: function (position, graphic) {
    //   const point = mars3d.LngLatPoint.fromCartesian(position)
    //   return (point.lng > 115 && point.lng < 117)
    // }
  })

  console.log("标绘完成", graphic.toJSON())

  // map.highlightEnabled = true
  // map.popup.enabled = true
}

export async function drawBrushLine(clampToGround: boolean) {
  const graphic = await graphicLayer.startDraw({
    type: "brushLine",
    style: {
      color: clampToGround ? "#ffff00" : "#3388ff",
      width: 3,
      clampToGround
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawPolygon(clampToGround: boolean) {
  const graphic = await graphicLayer.startDraw({
    type: "polygon" ,
    style: {
      color: clampToGround ? "#ffff00" : "#3388ff",
      opacity: 0.5,
      outline: true,
      outlineColor: "#ffffff",
      outlineWidth: 2.0,
      clampToGround
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawEllipse(clampToGround: boolean) {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "circle" : "circleP",
    style: {
      color: clampToGround ? "#ffff00" : "#3388ff",
      opacity: 0.6,
      outline: true,
      outlineColor: "#ffffff",
      outlineWidth: 2.0,
      clampToGround
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawRectangle(clampToGround: boolean) {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "rectangle" : "rectangleP",
    style: {
      color: clampToGround ? "#ffff00" : "#3388ff",
      opacity: 0.6,
      outline: true,
      outlineColor: "#ffffff",
      outlineWidth: 2.0,
      clampToGround
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function draPlane() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "plane" : "planeP",
    style: {
      color: "#00ff00",
      opacity: 0.8,
      plane_normal: "x",
      dimensions_x: 1000.0,
      dimensions_y: 1000.0
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function draWall(closure: boolean) {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "wall" : "wallP",
    style: {
      color: "#00ff00",
      opacity: 0.8,
      diffHeight: 400,
      closure // 是否闭合
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawBox() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "box" : "boxP",
    style: {
      color: "#00ff00",
      opacity: 0.6,
      dimensions_x: 1000.0,
      dimensions_y: 1000.0,
      dimensions_z: 1000.0
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawCylinder() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "cylinder" : "cylinderP",
    style: {
      fill: true,
      color: "#00ff00",
      opacity: 0.6,
      length: 1000
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawEllipsoid() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "ellipsoid" : "ellipsoidP",
    style: {
      fill: true,
      color: "#00ff00",
      opacity: 0.6
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawExtrudedPolygon() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "polygon" : "polygonP",
    style: {
      color: "#00ff00",
      opacity: 0.6,
      diffHeight: 300
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawExtrudedRectangle() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "rectangle" : "rectangleP",
    style: {
      color: "#00ff00",
      opacity: 0.6,
      diffHeight: 300
    }
  })

  console.log("标绘完成", graphic.toJSON())
}

export async function drawExtrudedCircle() {
  const graphic = await graphicLayer.startDraw({
    type: isEntityGraphic ? "circle" : "circleP",
    style: {
      color: "#00ff00",
      opacity: 0.6,
      diffHeight: 300
    }
  })

  console.log("标绘完成", graphic.toJSON())
}


export async function drawSwallowtailArrow() {




    const graphic = await graphicLayer.startDraw({
    type: "plotSwallowtailArrow",
    styleType: "polygon",
    style: {
      color: "#ff0000",
      opacity: 0.6,
      outline: true,
      outlineWidth: 3,
      outlineColor: "#ffffff",
      clampToGround: true
    }
  })

  console.log("标绘完成", graphic.toJSON())


}
export async function drawAttackArrow() {
  await graphicLayer.startDraw({
    type: "plotAttackArrow",
    style: { color: "#f00", opacity: 0.7 }
  })
}
export async function drawPincerArrow() {
  await graphicLayer.startDraw({
    type: "plotPincerArrow",
    style: { color: "#0f0", opacity: 0.7 }
  })
}

export function bindLayerContextMenu() {
  graphicLayer.bindContextMenu([
    {
      text: "开始编辑对象",
      icon: "fa fa-edit",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic || !graphic.hasEdit) {
          return false
        }
        return !graphic.isEditing
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          graphicLayer.startEditing(graphic)
        }
      }
    },
    {
      text: "停止编辑对象",
      icon: "fa fa-edit",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic || !graphic.hasEdit) {
          return false
        }
        return graphic.isEditing
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          graphic.stopEditing()
        }
      }
    },
    {
      text: "复制",
      icon: "fa fa-copy",
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          map.contextmenu.copyGraphic = graphic.toJSON() // map内置右键中"粘贴"菜单使用
          map.contextmenu.copyGraphic.layerId = graphicLayer.id
        }
      }
    },
    {
      text: "剪切",
      icon: "fa fa-scissors",
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        if (graphic) {
          map.contextmenu.copyGraphic = graphic.toJSON() // map内置右键中"粘贴"菜单使用
          map.contextmenu.copyGraphic.layerId = graphicLayer.id

          graphic.remove(true) // 移除原有对象
        }
      }
    },
    {
      text: "还原编辑(还原到初始)",
      icon: "fa fa-pencil",
      show: (event) => {
        function hasRestore(graphic) {
          if (!graphic || !graphic.hasEdit || !graphic.isEditing) {
            return false
          }
          return graphic.editing?.hasRestore()
        }

        const graphic = event.graphic
        if (hasRestore(graphic)) {
          return true
        }
        if (graphic.isPrivate && graphic.parent) {
          return hasRestore(graphic.parent) // 右击是编辑点时
        }
        return false
      },
      callback: (event) => {
        const graphic = event.graphic
        if (graphic.editing?.restore) {
          graphic.editing.restore() // 撤销编辑，可直接调用
        } else if (graphic.parent?.editing?.restore) {
          graphic.parent.editing.restore() // 右击是编辑点时
        }
      }
    },
    {
      text: "撤销编辑(还原到上一步)",
      icon: "fa fa-pencil",
      show: (event) => {
        function hasRevoke(graphic) {
          if (!graphic || !graphic.hasEdit || !graphic.isEditing) {
            return false
          }
          return graphic.editing?.hasRevoke()
        }

        const graphic = event.graphic
        if (hasRevoke(graphic)) {
          return true
        }
        if (graphic.isPrivate && graphic.parent) {
          return hasRevoke(graphic.parent) // 右击是编辑点时
        }
        return false
      },
      callback: (event) => {
        const graphic = event.graphic
        if (graphic.editing?.revoke) {
          graphic.editing.revoke() // 撤销编辑，可直接调用
        } else if (graphic.parent?.editing?.revoke) {
          graphic.parent.editing.revoke() // 右击是编辑点时
        }
      }
    },
    {
      text: "删除对象",
      icon: "fa fa-trash-o",
      show: (event) => {
        const graphic = event.graphic
        if (!graphic || graphic.isDestroy || graphic.isPrivate || graphic.graphicIds) {
          return false
        } else {
          return true
        }
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return
        }
        const parent = graphic.parent // 右击是编辑点时
        graphicLayer.removeGraphic(graphic)
        if (parent) {
          graphicLayer.removeGraphic(parent)
        }
      }
    },
    {
      text: "计算长度",
      icon: "fa fa-medium",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        return (
          graphic.type === "polyline" ||
          graphic.type === "polylineP" ||
          graphic.type === "curve" ||
          graphic.type === "curveP" ||
          graphic.type === "polylineVolume" ||
          graphic.type === "polylineVolumeP" ||
          graphic.type === "corridor" ||
          graphic.type === "corridorP" ||
          graphic.type === "wall" ||
          graphic.type === "wallP"
        )
      },
      callback: (e) => {
        const graphic = e.graphic
        const strDis = mars3d.MeasureUtil.formatDistance(graphic.distance)
        console.log("该对象的长度为:" + strDis)
      }
    },
    {
      text: "计算周长",
      icon: "fa fa-medium",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        return (
          graphic.type === "circle" ||
          graphic.type === "circleP" ||
          graphic.type === "rectangle" ||
          graphic.type === "rectangleP" ||
          graphic.type === "polygon" ||
          graphic.type === "polygonP"
        )
      },
      callback: (e) => {
        const graphic = e.graphic
        const strDis = mars3d.MeasureUtil.formatDistance(graphic.distance)
        console.log("该对象的周长为:" + strDis)
      }
    },
    {
      text: "计算面积",
      icon: "fa fa-reorder",
      show: function (e) {
        const graphic = e.graphic
        if (!graphic) {
          return false
        }
        return (
          graphic.type === "circle" ||
          graphic.type === "circleP" ||
          graphic.type === "rectangle" ||
          graphic.type === "rectangleP" ||
          graphic.type === "polygon" ||
          graphic.type === "polygonP" ||
          graphic.type === "scrollWall" ||
          graphic.type === "water"
        )
      },
      callback: (e) => {
        const graphic = e.graphic
        const strArea = mars3d.MeasureUtil.formatArea(graphic.area)
        console.log("该对象的面积为:" + strArea)
      }
    }
  ])
}



// 面板样式
export function addDemoGraphic() {
  const width = 240
  const height = 160
  const graphic = new mars3d.graphic.DivGraphic({
    position: [117.083534, 31.654421],
    style: {
      html: `
         <div id="tech-popup" style="
    width:${width}px;
    height:${height}px;
    background-image:url(/left-s.png);
    background-size:100% 100%;
    border-radius:12px;
    box-shadow:0 2px 8px rgba(0,0,0,0.15);
    border:1px solid #e5e7eb;
    position:relative;
    display:flex;
    flex-direction:column;
  ">
    <div style="
      display:flex;
      align-items:center;
      justify-content:space-between;
      padding:8px 16px;
      border-bottom:1px solid #f3f4f6;
      border-radius:12px 12px 0 0;
    ">
      <span style="font-size:16px;font-weight:bold;color:#fff;">科技点</span>
      <button id="btn-close-popup" style="
        color:#fff;
        background:transparent;
        border:none;
        font-size:20px;
        font-weight:bold;
        cursor:pointer;
        line-height:1;
      ">×</button>
    </div>
    <div style="flex:1;padding:16px;color:#374151;font-size:14px;">
      这里
    </div>
  </div>
      `,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.TOP,
      offset: {
        x: -width / 2,
        y: -height
      },
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 100000)
    },
    attr: { remark: "自定义弹框" }
  })
  graphic.on(mars3d.EventType.load, function (event) {
    const container = event.graphic.container // popup对应的DOM
    const btnClose = container.querySelector("#btn-close-popup") as HTMLElement
    if (btnClose) {
      btnClose.addEventListener("click", (e: MouseEvent) => {
        e.stopPropagation()
        graphicLayer.removeGraphic(event.graphic)
      })
    }
  })
  graphicLayer.addGraphic(graphic)
}

export function addAnimatedIconPoint() {
  const graphic = new mars3d.graphic.DivGraphic({
    position: [117.085101, 31.654251],
    hasEdit: false, // 不可编辑
    style: {
      html: `
        <div style="position:relative;width:120px;height:170px;pointer-events:auto;">
          <div class="ripple" style="position:absolute;left:50%;top:140px;transform:translate(-50%,-50%);width:120px;height:120px;z-index:1;">
            <span class="ripple-circle"></span>
            <span class="ripple-circle"></span>
            <span class="ripple-circle"></span>
          </div>
          <div class="icon-float" style="position:absolute;left:50%;top:80px;transform:translate(-50%,-50%);z-index:2;">
            <img src="https://data.mars3d.cn/img/marker/mark-red.png" style="width:48px;height:48px;object-fit:contain;display:block;" />
          </div>
        </div>
        <style>
          .icon-float {
            animation: floatUpDown 1.6s ease-in-out infinite;
          }
          @keyframes floatUpDown {
            0% { transform: translate(-50%,-50%) translateY(0); }
            50% { transform: translate(-50%,-50%) translateY(-18px); }
            100% { transform: translate(-50%,-50%) translateY(0); }
          }
          .ripple-circle {
            position: absolute;
            left: 50%;
            top: 50%;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: rgba(255, 0, 0, 0.18);
            border: 2px solid #ff0000;
            transform: translate(-50%, -50%);
            animation: rippleSpread 1.2s linear infinite;
            opacity: 0.8;
          }
          .ripple-circle:nth-child(2) {
            animation-delay: 0.4s;
          }
          .ripple-circle:nth-child(3) {
            animation-delay: 0.8s;
          }
          @keyframes rippleSpread {
            0% {
              width: 0;
              height: 0;
              opacity: 0.8;
            }
            70% {
              opacity: 0.25;
            }
            100% {
              width: 120px;
              height: 120px;
              opacity: 0;
            }
          }
        </style>
      `,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 100000)
    },
    attr: { remark: "动效图标点" }
  })
  graphicLayer.addGraphic(graphic)
}



// 1. 添加贴地红色扩散波纹
export function addGroundRippleAtModel() {
  const lng = 117.085556
  const lat = 31.653611
  const height = 30.1
  const positions = getCirclePositions(lng, lat, height, 30, 30)
  const rippleGraphic = new mars3d.graphic.PolygonPrimitive({
    positions: positions,
    hasEdit: false, // 不可编辑
    style: {
      materialType: mars3d.MaterialType.CircleWave,
      color: "#ff0000",
      opacity: 0.5,
      count: 3,   // 增加同心环数量
      speed: 10, // 加速波纹扩散
      waveWidth: 0.3,   // 波纹宽度（0.1-0.5）
      gradient: 0.6,    // 颜色渐变强度（0-1）
      glowPower: 0.8    // 辉光强度（增强警示效果）
    }
  });
  graphicLayer.addGraphic(rippleGraphic);
}

// 2. 添加上下跳动的锚定图标
export function addBouncingBillboardAtModel() {
  const lng = 117.085556
  const lat = 31.653611
  const baseHeight = 30.1
  let t = 0
  const Cesium = mars3d.Cesium
  const graphic = new mars3d.graphic.BillboardEntity({
    position: new mars3d.LngLatPoint(lng, lat, baseHeight),
    hasEdit: false,
    style: {
      image: "https://data.mars3d.cn/img/marker/mark-red.png",
      scale: 1.2,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    },
    attr: { remark: "跳动锚定图标" }
  });
  graphicLayer.addGraphic(graphic);

  function animate() {
    t += 0.04
    const offset = Math.abs(Math.sin(t)) * 10
    if (graphic && graphic.position !== undefined) {
      graphic.position = new mars3d.LngLatPoint(lng, lat, baseHeight + offset)
      requestAnimationFrame(animate)
    }
  }
  animate()
}

function getCirclePositions(lng, lat, height, radius, count = 80) {
  const arr = []
  for (let i = 0; i < count; i++) {
    const angle = (i / count) * 2 * Math.PI
    // 计算经纬度偏移
    const dx = (radius / 111319.49) * Math.cos(angle) // 1度经度约等于111319.49米
    const dy = (radius / 110946.26) * Math.sin(angle) // 1度纬度约等于110946.26米
    arr.push([lng + dx, lat + dy, height])
  }
  return arr
}

export function addtopBGraphic() {
    const lng = 117.085556
  const lat = 31.653611
  const baseHeight = 30.1
  const graphic = new mars3d.graphic.BillboardEntity({
    position: new mars3d.LngLatPoint(lng, lat, baseHeight),
    style: {
      image: "https://data.mars3d.cn/img/marker/lace-red.png",
      scale: 1.0,
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      clampToGround: true,
      // heightReference: new Cesium.CallbackProperty(function (time) {
      //   if (map.scene.mode !== Cesium.SceneMode.SCENE3D) {
      //     return Cesium.HeightReference.NONE //解决2D贴地对象不显示问题
      //   } else {
      //     return Cesium.HeightReference.CLAMP_TO_GROUND
      //   }
      // }, false),
      label: { text: "鼠标移入会放大", pixelOffsetY: -50 },
      // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
      highlight: {
        scale: 1.5
      }
    },
    attr: { remark: "示例2" }
  })

  graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
     if (graphic.startBounce) {
      graphic.startBounce()
  }
}



// 开始绘制
export async function startDrawGraphic() {
  const graphic = await graphicLayer.startDraw({
    type: "div",
    style: {
      html: `<div class="marsImgPanel2">
                    <div class="title">测试DIV点</div>
                    <div class="content">此处可以绑定任意Html代码和css效果</div>
                </div >`,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM
    }
  })
  console.log("标绘完成", graphic.toJSON())
}


// 路径规划
let startGraphic, endGraphic
/**
 * 起点按钮
 *
 * @export
 * @param {number} type 不同方式路线查询
 * @returns {string}
 */
export function startPoint(type) {
  if (startGraphic) {
    startGraphic.remove()
    startGraphic = null
  }

  return graphicLayer
    .startDraw({
      type: "billboard",
      style: {
        image: "https://data.mars3d.cn/img/marker/route-start.png",
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      }
    })
    .then((graphic) => {
      startGraphic = graphic
      const point = graphic.point
      point.format()
      // 触发自定义事件，改变输入框的值
      queryRouteServe(type)

      return point.lng + "," + point.lat
    })
}

/**
 * 终点按钮
 *
 * @export
 * @param {number} type 不同方式路线查询
 * @returns {string}
 */
export function endPoint(type) {
  if (endGraphic) {
    endGraphic.remove()
    endGraphic = null
  }

  return graphicLayer
    .startDraw({
      type: "billboard",
      style: {
        image: "https://data.mars3d.cn/img/marker/route-end.png",
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      }
    })
    .then((graphic) => {
      endGraphic = graphic
      const point = graphic.point
      point.format()
      queryRouteServe(type)

      return point.lng + "," + point.lat
    })
}



function queryRouteServe(type) {
  if (!startGraphic || !endGraphic) {
    return
  }

  // graphicLayer.clear()

  query.query({
    type: Number(type),
    points: [startGraphic.coord, endGraphic.coord],
    success: function (data) {
      const firstItem = data.paths[0]
      const points = firstItem.points
      if (!points || points.length < 1) {
        return
      }

      const time = mars3d.Util.formatTime(firstItem.allDuration)
      const distance = mars3d.MeasureUtil.formatDistance(firstItem.allDistance)
      const html = "<div>总距离：" + distance + "<br/>所需时间：" + time + "</div>"

      const graphic = new mars3d.graphic.PolylineEntity({
        positions: points,
        style: {
          clampToGround: true,
          material: Cesium.Color.AQUA.withAlpha(0.8),
          width: 5
        },
        attr: firstItem,
        popup: html
      })
      graphicLayer.addGraphic(graphic)

      const allTime = mars3d.Util.formatTime(firstItem.allDuration)
      const allDistance = mars3d.MeasureUtil.formatDistance(firstItem.allDistance)
      let dhHtml = ""
      for (let i = 0; i < firstItem.steps.length; i++) {
        const item = firstItem.steps[i]
        dhHtml += item.instruction + "；"
      }

      // eventTarget.fire("analyse", { allTime, allDistance, dhHtml })
      console.log("analyse", { allTime, allDistance, dhHtml })
    },
    error: function (msg) {
      console.log('规划路径出错了')
    }
  })
}


// 框选范围
let drawGraphic

// 框选查询 矩形
export async function drawRectangleFW() {
  drawGraphic = await map.graphicLayer.startDraw({
    type: "rectangle",
    style: {
      color: "#00FF00",
      opacity: 0.3,
      outline: true,
      outlineColor: "#ffffff"
      // clampToGround: true
    }
  })
  console.log("框选矩形：", drawGraphic.toGeoJSON({ outline: true }))
}

// 框选查询   圆
export async function drawCircle() {
  drawGraphic = await map.graphicLayer.startDraw({
    type: "circle",
    style: {
      color: "#00FF00",
      opacity: 0.3,
      outline: true,
      outlineColor: "#ffffff"
      // clampToGround: true
    }
  })
  console.log("框选圆：", drawGraphic.toGeoJSON({ outline: true }))
}

// 框选查询   多边行
export async function drawPolygonFW() {
  drawGraphic = await map.graphicLayer.startDraw({
    type: "polygon",
    style: {
      color: "#00FF00",
      opacity: 0.3,
      outline: true,
      outlineColor: "#ffffff"
      // clampToGround: true
    }
  })
  console.log("框选多边行：", drawGraphic.toGeoJSON())
}
